/**
 * @author nttdocomo
 */
define(function(require) {
	require("../util/keyNav");
	aries.klass("aries.view.BoundListKeyNav", aries.util.KeyNav.extend({

		/**
		 * @cfg {Ext.view.BoundList} boundList (required)
		 * The {@link Ext.view.BoundList} instance for which key navigation will be managed.
		 */

		initialize : function(el, config) {
			var me = this;
			me.boundList = config.boundList;
			aries.util.KeyNav.prototype.initialize.apply(this, [el, $.extend({}, config, me.defaultHandlers)]);
		},

		defaultHandlers : {
			up : function() {
				var me = this, boundList = me.boundList, allItems = boundList.all, oldItem = boundList.highlightedItem, oldItemIdx = oldItem ? boundList.indexOf(oldItem) : -1, newItemIdx = oldItemIdx > 0 ? oldItemIdx - 1 : allItems.length - 1;
				//wraps around
				me.highlightAt(newItemIdx);
			},

			down : function() {
				var me = this, boundList = me.boundList, allItems = boundList.all, oldItem = boundList.highlightedItem, oldItemIdx = oldItem ? boundList.indexOf(oldItem) : -1, newItemIdx = oldItemIdx < allItems.length - 1 ? oldItemIdx + 1 : 0;
				//wraps around
				me.highlightAt(newItemIdx);
			},

			pageup : function() {
				//TODO
			},

			pagedown : function() {
				//TODO
			},

			home : function() {
				this.highlightAt(0);
			},

			end : function() {
				var me = this;
				me.highlightAt(me.boundList.all.getCount() - 1);
			},

			enter : function(e) {
				this.selectHighlighted(e);
			}
		},

		/**
		 * Highlights the item at the given index.
		 * @param {Number} index
		 */
		highlightAt : function(index) {
			var boundList = this.boundList, item = boundList.all.eq(index);
			if (item) {
				boundList.highlightItem(item);
				item.scrollIntoView(false)//scrollChildIntoView(item, false);
			}
		},

		/**
		 * Triggers selection of the currently highlighted item according to the behavior of
		 * the configured SelectionModel.
		 */
		selectHighlighted : function(e) {
			var me = this, boundList = me.boundList, highlighted = boundList.highlightedItem, selModel = boundList.getSelectionModel();
			if (highlighted) {
				selModel.selectWithEvent(boundList.getRecord(highlighted), e);
			}
		}
	}))
})
